package com.ruoyi.quartz.task;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.PremaidFood;
import com.ruoyi.system.domain.Stock;
import com.ruoyi.system.mapper.PremaidFoodMapper;
import com.ruoyi.system.mapper.StockMapper;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 定时清理过期库存
 *
 * @author liukangzu
 */
@Component("FoodTask")
public class FoodTask {
    //注入Mapper
    private PremaidFoodMapper premaidFoodMapper = SpringUtils.getBean(PremaidFoodMapper.class);
    private StockMapper stockMapper = SpringUtils.getBean(StockMapper.class);

    public void cleanExpiredStock(){
        //获取菜品列表及库存列表
        List<PremaidFood> premaidFoods = premaidFoodMapper.selectPremaidFoodList(null);
        List<Stock> stocks = stockMapper.selectStockList(null);

        //获取当前时间
        LocalDate now = LocalDate.now();

        for (Stock stock : stocks) {
            //获取生产时间
            Date stockProductionTime = stock.getStockProductionTime();
            LocalDate productionTime = stockProductionTime.toInstant()
                    .atZone(ZoneId.systemDefault()) // 使用系统默认时区
                    .toLocalDate();

            //获取保质期
            PremaidFood premaidFood = premaidFoodMapper.selectPremaidFoodByPremaidFoodId(stock.getPremaidFood().getPremaidFoodId());
            Integer shelfLife = premaidFood.getPremaidFoodTime();

            //计算过期日期
            LocalDate expirationDate = productionTime.plusDays(shelfLife);

            //清理过期库存
            if (expirationDate.isBefore(now)){
                stockMapper.cleanStockByStockId(stock.getStockId());
            }
        }
    }
}
